package com.aliware.tianchi;

import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;

/**
 * @author daofeng.xjf
 *
 * 客户端过滤器
 * 可选接口
 * 用户可以在客户端拦截请求和响应,捕获 rpc 调用时产生、服务端返回的已知异常。
 */
@Activate(group = Constants.CONSUMER)
public class TestClientFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try{

//            if (LoadBalanceHelper.DiffSmall() <= 0 && LoadBalanceHelper.DiffMedium() <=0
//            && LoadBalanceHelper.DiffLarge() <=0)
//            {
//                return null;
//            }else
//            {
                Result result = invoker.invoke(invocation);
                return result;
//            }

        }catch (Exception e){
            throw e;
        }

    }

    @Override
    public Result onResponse(Result result, Invoker<?> invoker, Invocation invocation) {
        int port = invoker.getUrl().getPort();
        if (port == 20880)
        {
            if (LoadBalanceHelper.CurrentSmall.contains(invoker.hashCode()))
                LoadBalanceHelper.CurrentSmall.remove(invoker.hashCode());

        }else if (port == 20870)
        {
            if (LoadBalanceHelper.CurrentMedium.contains(invoker.hashCode()))
                LoadBalanceHelper.CurrentMedium.remove(invoker.hashCode());
        }else if (port == 20890)
        {
            if (LoadBalanceHelper.CurrentLarge.contains(invoker.hashCode()))
                LoadBalanceHelper.CurrentLarge.remove(invoker.hashCode());
        }
        System.out.println(LoadBalanceHelper.CurrentLarge.size() + ","
            +LoadBalanceHelper.CurrentMedium.size() + "," +
                LoadBalanceHelper.CurrentSmall.size());
        return result;
    }
}
